package com.itheima.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.BrowseGoodsRecord;
import com.itheima.pojo.Item;
import com.itheima.pojo.User;
import com.itheima.service.BrowseGoodsRecordService;
import com.itheima.service.ItemService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.stream.Collectors;

@WebServlet("/addBrowseGoodsRecordServlet")
public class AddBrowseGoodsRecordServlet extends HttpServlet {
    private BrowseGoodsRecordService service = new BrowseGoodsRecordService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置编码（重要，避免乱码）
        request.setCharacterEncoding("utf-8");

        // 从HttpServletRequest对象中获取输入流，并读取JSON字符串
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }

        String jsonString = sb.toString();

        // 将JSON字符串转换为JSON对象
        JSONObject jsonObj = JSON.parseObject(jsonString);

        // 获取JSON对象中的值
        double duration = jsonObj.getDouble("duration");
        String itemName = jsonObj.getString("itemName");

        // 通过session获取user对象
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        Integer userId = user.getId();

        BrowseGoodsRecord browseGoodsRecord = new BrowseGoodsRecord();
        browseGoodsRecord.setDuration(duration);
        browseGoodsRecord.setItemName(itemName);
        browseGoodsRecord.setUserId(userId);

        service.add(browseGoodsRecord);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
